#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.bean;

import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.PersistenceException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ${package}.filter.RememberMeFilter;
import ${package}.model.Usuario;
import ${package}.negocio.api.UsuarioNegocio;
import br.com.framework.apresentacao.bean.BaseBean;
import br.com.framework.negocio.exception.NegocioException;
import br.com.framework.util.security.CryptoUtils;

@Named
@SessionScoped
public class LoginBean extends BaseBean {
	
	public static final String 	COOKIE_REMEMBER_ME = "${rootArtifactId}-r3m-c00k";
	public static final int 	COOKIE_REMEMBER_ME_MAX_AGE = 60 * 60 * 24 * 30; // 30 dias

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private UsuarioNegocio usuarioNegocio;
	
	private Usuario usuario;
	
	private String login;
	private String password;
	private boolean manterLogado;
	
	/**
	 * @return
	 */
	public String login() {
		String outcome = "/pages/protected/main" + PARAM_FACES_REDIRECT_TRUE;
		ExternalContext exContext = getExternalContext();
	    HttpServletRequest request = (HttpServletRequest) exContext.getRequest();
	    HttpServletResponse response = (HttpServletResponse) exContext.getResponse();
	    try {
	    	if (request.getUserPrincipal() != null) {
	    		request.logout();
	    	}
			request.login(login, CryptoUtils.getEncryptedSha1(password));
			if (isManterLogado()) {
				Usuario usuario = usuarioNegocio.findByLogin(login);
				if (usuario != null) {
					String rememberCookie = RememberMeFilter.getRemeberCookieValue(request);
					if (rememberCookie == null || 
							(usuario.getUuidLogado() != null && 
							!usuario.getUuidLogado().equals(rememberCookie))) {
						rememberCookie = RememberMeFilter.createRememberCookie(response);
						usuario.setUuidLogado(rememberCookie);
						usuario.setConfirmaSenha(usuario.getSenha());
				        try {
							usuarioNegocio.update(usuario);
						} catch (PersistenceException e) {
							LOGGER.error("Falha de persistência ao atualizar o Usuario com o cookie de manter logado.", e);
						} catch (NegocioException e) {
							LOGGER.error("Erro de negocio ao atualizar o Usuario com o cookie de manter logado.", e);
						}
					}
				}
			} else {
				removerRememberCookie();
			}
		} catch (ServletException e) {
			LOGGER.error("Erro no login", e);
			facesMessages.addMessageError(null, "label.mensagem.loginSenhaInvalido");
			outcome = "/pages/public/loginError";
		} finally {
			password = "";
		}
        return outcome;
	}
	
	/**
	 * Remove o cookie de manter logado
	 */
	public void removerRememberCookie() {
		String cookieValue = getCookieValue(COOKIE_REMEMBER_ME);
		if (cookieValue != null) {
			HttpServletResponse response = (HttpServletResponse) getExternalContext().getResponse();
			RememberMeFilter.removeRememberCookie(response);
		}
	}
	
	/**
	 * @return
	 */
	public Usuario getUsuario() {
		if (usuario == null) {
			if (getExternalContext().getUserPrincipal() != null) {
				usuario = new Usuario();
				usuario.setLogin(getExternalContext().getUserPrincipal().getName());
				List<Usuario> list = usuarioNegocio.findByExample(usuario);
				if (list != null && list.size() == 1) {
					usuario = list.get(0);
				} else {
					usuario.setLogin(getExternalContext().getUserPrincipal().getName());
				}
			}
		}
		return usuario;
	}

	/**
	 * @return
	 */
	public String logout() {
		ExternalContext externalContext = getExternalContext();
	    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
	    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
	    try {
			request.logout();
		} catch (ServletException e) {
			LOGGER.error("Erro no logout.", e);
		}
	    request.getSession(false).invalidate();
	    RememberMeFilter.removeRememberCookie(response);
		getFacesMessages().addMessageInfo(null, "label.mensagem.logoutSucesso");
		return "/index";
	}

	/**
	 * @return the login
	 */
	public String getLogin() {
		return login;
	}

	/**
	 * @param login the login to set
	 */
	public void setLogin(String login) {
		this.login = login;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String senha) {
		this.password = senha;
	}

	/**
	 * @return the manterLogado
	 */
	public boolean isManterLogado() {
		return manterLogado;
	}

	/**
	 * @param manterLogado the manterLogado to set
	 */
	public void setManterLogado(boolean manterLogado) {
		this.manterLogado = manterLogado;
	}

}
